import imaplib
import email
from email.header import decode_header

# Outlook邮箱的IMAP服务器地址和端口
IMAP_SERVER = '10.202.144.31'
IMAP_PORT = 143

# 用户的邮箱地址和密码
username = 'bi@feiniu.com'
password = 'Fn123!@#'

# 登录到IMAP服务器
mail = imaplib.IMAP4_SSL(IMAP_SERVER, IMAP_PORT)
mail.login(username, password)

# 选择邮箱文件夹，通常是 "INBOX"
mail.select('INBOX')

# 搜索未读邮件
status, messages = mail.search(None, 'UNSEEN')

# 获取邮件ID列表
email_ids = messages[0].split()

# 遍历每一封未读邮件
for email_id in email_ids:
    # 获取邮件数据
    res, msg = mail.fetch(email_id, '(RFC822)')
    
    # 邮件内容
    for response_part in msg:
        if isinstance(response_part, tuple):
            # 解析邮件
            msg = email.message_from_bytes(response_part[1])
            
            # 解码邮件主题
            subject, encoding = decode_header(msg['Subject'])[0]
            if isinstance(subject, bytes):
                subject = subject.decode(encoding if encoding else 'utf-8')
            
            # 打印邮件主题和发件人
            print(f'From: {msg["From"]}')
            print(f'Subject: {subject}')
            print('-' * 50)

# 登出
mail.logout()
